package com;


import java.io.IOException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.util.Date;
import java.util.List;

import javax.servlet.http.*;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;

import com.google.appengine.api.datastore.FetchOptions;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.Query.Filter;
import com.google.appengine.api.datastore.Query.FilterPredicate;
import com.google.appengine.api.datastore.Query.FilterOperator;
import com.google.appengine.api.datastore.Query.CompositeFilterOperator;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;


public class Voteforpost extends HttpServlet{

	/**
	 * 
	 */
	private static final long serialVersionUID = 6290597370694491118L;

	public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		
		UserService userService = UserServiceFactory.getUserService();
		User user = userService.getCurrentUser();
		if (user == null) {
	        resp.sendRedirect(userService.createLoginURL(req.getRequestURI()));
	    }
		
		String type = req.getParameter("type");
		String vid = hash(req.getParameter("vid"));
		
		String pid = req.getParameter("pid");
		String getUID = hash(user.getUserId());
		if(!getUID.equals(vid)){
			resp.getWriter().print("Are you attacker?");
			return;
		}
		
		Filter vidfind = new FilterPredicate("vid",FilterOperator.EQUAL,vid);
		Filter pidfind = new FilterPredicate("pid",FilterOperator.EQUAL,pid);
		Filter findboth = CompositeFilterOperator.and(vidfind,pidfind);
		
		Query q = new Query("Vote").setFilter(findboth);
		
        DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
        List<Entity> res = datastore.prepare(q).asList(FetchOptions.Builder.withDefaults());
        if(res.isEmpty()){
        	Entity v = new Entity("Vote");
        	v.setProperty("pid", pid);
        	v.setProperty("vid", vid);
        	v.setProperty("date", new Date());
        	datastore.put(v);
        	
        	Key k = KeyFactory.stringToKey(pid);
        	
        	try {
				Entity e = datastore.get(k);
				if(type.equals("voteyes")){
					Long l =  (Long) e.getProperty("yes");
					e.setProperty("yes", l+1);
				}else if(type.equals("voteno")){
					Long l = (Long) e.getProperty("no");
					e.setProperty("no", l+1);
				}
				
				datastore.put(e);
			} catch (Exception e) {
				e.printStackTrace();
			}
        	
        	resp.getWriter().print("Voted!");
        	
        }else{
        	resp.getWriter().print("Already Voted!");
        }
		
	}
	
	public String hash(String i){
		String digest = "null";
		try{
		MessageDigest md = MessageDigest.getInstance("MD5");
		md.update(i.getBytes());
		byte[] md5sum = md.digest();
		BigInteger bigInt = new BigInteger(1, md5sum);
		digest = bigInt.toString(16);
		while ( digest.length() < 32 ) {
		    digest = "0"+digest;
		}
		}catch(Exception e){
			e.printStackTrace();
		}
		return digest;
	}
}